$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/product/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
            { label: '商品图片', name: 'productimg', index: 'productimg', width: 80,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.productimg!=null&&rowdata.productimg!=''){
                        return '<img src='+rowdata.productimg+' width="50" height="50"/>';
                    }else{
                        return '';
                    }

                } },
			{ label: '商品名称', name: 'productname', index: 'productName', width: 100,formatter: function(cellvalue, options, rowdata) {
                    return rowdata.productname+'<br/>'+rowdata.barcode;

                } },
			{ label: '成本价', name: 'costprice', index: 'costPrice', width: 50 },
			{ label: '销售价', name: 'sellprice', index: 'sellPrice', width: 50},
			{ label: '商品分类', name: 'categoryid', index: 'categoryid', width: 80,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.categoryid!=null&&rowdata.categoryid!=""){
                        var groupname = "";
                        var arr = rowdata.categoryid.split(",");
                        for(var i=0;i<arr.length;i++){
                            $.ajax({
                                type: "POST",
                                async:false,
                                url: baseURL + "sys/productcategory/info/"+parseInt(arr[i]),
                                success: function(r){
                                    groupname +=r.productcategory.name;
                                    if(i !=arr.length-1){
                                        groupname +="/";
                                    }

                                }
                            });
                        }
                        return groupname;
                    }else{
                        return '未分组';
                    }


                } },
			{ label: '创建时间', name: 'createtime', index: 'createtime', width: 80 },
            { label: '操作', name: 'sy', width: 120,formatter: function(cellvalue, options, rowdata) {
                    return "<a style='cursor:pointer;' onclick='vm.update("+ rowdata.id +")'>" +
                        "&nbsp;编辑</a>&nbsp;&nbsp;" +
						"<a style='cursor:pointer;' onclick='vm.del("+ rowdata.id +")'>" +
						"&nbsp;删除</a>&nbsp;&nbsp;";
                } }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    vm.queryCategory();
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        fileList1: [],
        q:{
            name:null,
            categoryid:null
        },
        groupList: [],
		showList: true,
		title: null,
		product: {}

	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.product = {};
            vm.fileList1 =  [];
            vm.product.infinitestock = 0;
            vm.product.stockwarning = 0;
            vm.product.istackout =  1;
            vm.getGroup();
		},
		update: function (id) {

			vm.showList = false;
            vm.title = "修改";
            vm.groupList = [];
            vm.getGroup();
            
            vm.getInfo(id);
            if(vm.product.categoryid!=null&&vm.product.categoryid!=""){
                var arr = vm.product.categoryid.split(",");
                for(var i=0;i<arr.length;i++){
                    vm.groupList.push(parseInt(arr[i]));
                    $("#"+parseInt(arr[i])).css("border","1px solid #1e8feb").css("color","#1e8feb").css("background-color","#e8f4fd");
                }
            }
		},
		saveOrUpdate: function (event) {
			var url = vm.product.id == null ? "sys/product/save" : "sys/product/update";
            vm.product.productimg = '';
            if(vm.fileList1.length>0){
                vm.product.productimg = vm.fileList1[0].url;
            }
            vm.product.categoryid = "";
            if(vm.groupList.length>0){
                for(var i=0;i<vm.groupList.length;i++){
                    vm.product.categoryid +=vm.groupList[i];
                    if(i!=vm.groupList.length-1){
                        vm.product.categoryid +=",";
                    }
                }
            }
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.product),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        getBarcode: function(){
            var bc = $("input[name='barcode']:checked").val();

            if(bc == 2){
                $("#barcode").hide();
            }
            if(bc == 1){
                $("#barcode").show();
            }
        },
        takeOut: function(){
            var bc = $("input[name='istackout']:checked").val();

            if(bc == 0){
                $("#outprice").show();
                $("#infinitestock").show();
            }
            if(bc == 1){
                $("#outprice").hide();
                $("#infinitestock").hide();
            }

        },
        infiniteStock: function () {
            var bc = $("input[name='infinitestock']:checked").val();

            if(bc == 0){
                $("#outstock").hide();
            }
            if(bc == 1){
                $("#outstock").show();
            }
        },
        checkGroup: function(id){
            var ys = $("#"+id).attr("style");
            if(ys !="" && typeof ys!="undefined"){

                $("#"+id).attr("style","");
                var groupList1 = [];
                if(vm.groupList.length>0){
                    for(var i=0;i<vm.groupList.length;i++){
                        if(vm.groupList[i]!=id){
                            groupList1.push(vm.groupList[i]);
                        }
                    }
                }
                vm.groupList = groupList1;
            }else{
                vm.groupList.push(id);
                $("#"+id).css("border","1px solid #1e8feb").css("color","#1e8feb").css("background-color","#e8f4fd");
            }

        },
		del: function (id) {
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/product/delete/"+id,
                    contentType: "application/json",
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        handleRemove1: function(file, fileList) {
            console.log(fileList);
            if(fileList.length>0){
                vm.fileList1 = [];
                for(var i=0;i<fileList.length;i++){
                    vm.fileList1.push({name: fileList[i].name,url: fileList[i].url});

                }
            }
            console.log(vm.fileList1);

        },
        handlePreview: function(file) {
            console.log(file);
        },

        handsuccess1: function(response, file, fileList) {
            vm.fileList1.push({name: response.url,url: response.url});

        },
		getInfo: function(id){
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/product/info/"+id,
                success: function(r){
                    vm.product = r.product;
                    vm.fileList1 = [];
                    if(r.product.productimg!=null&&r.product.productimg!=''){
                        vm.fileList1.push({name: r.product.productimg,url: r.product.productimg});
                    }

                }
            });
		},
        queryCategory: function(){
            $("#category_id").html("");
            $.get(baseURL + "sys/productcategory/alllist", function(r){
                var temp = "<option value=''></option><option value='0'>未分组</option>";
                $.each(r.alllist, function (i) {

                    temp +="<option value='"+r.alllist[i].id+"'>"+r.alllist[i].name+"</option>";

                });
                $("#category_id").append(temp);

            });
        },
        getGroup: function(){
            $("#group").html("");
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/productcategory/alllist/",
                success: function(r){
                    var temp = "";
                    if(r.alllist!=null&&r.alllist.length>0){
                        $.each(r.alllist, function (i) {

                            temp +="<a class='btn btn-default' onclick='vm.checkGroup("+r.alllist[i].id+")' " +
                                "id='"+r.alllist[i].id+"'>"+r.alllist[i].name+"</a>&nbsp;&nbsp;";

                        });
                    }else{
                        temp = "您暂未对商品进行分组";
                    }

                    $("#group").append(temp);

                }
            });

        },
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.name,'categoryid':vm.q.categoryid},
                page:page
            }).trigger("reloadGrid");
		}
	}
});